import random
import requests
import json
from frame_work.type_file import (
    Type,
    Source
)
from frame_work.util import (
    check_tid,
    change_user_account_status,
    assert_result_dict,
    get_sql_info,
    bind_tb
)
from frame_work.logger import Logger
from frame_work.setting import *
from frame_work.yaml_file import YAML
from frame_work.login import AppLogin, PcLogin
from frame_work import menu_list

logger = Logger(__name__).get_logger()


class Submit(object):
    app_type = [
        "TYPE_APP_SEARCH",
        "TYPE_APP_TAO",
        "TYPE_APP_ORDER",
        "TYPE_MOBILE_TAO_SEARCH",
        "TYPE_PAY_APP",
        "TYPE_APP_ORDER_SEARCH",
        "TYPE_APP_SCAN_SEARCH",
        "TYPE_MULTIMODE",
        "TYPE_APP_PACKAGE",
        "TYPE_BRAND",
        "TYPE_PINGOU",
        "TYPE_REWARD",
        "TYPE_TEJIA"]
    need_verify_order_way = [
        'TYPE_MOBILE_TAO_SEARCH',
        'TYPE_APP_SCAN_SEARCH',
        'TYPE_APP_ORDER_SEARCH',
        "TYPE_PINGOU"]  # 根据来源需要验证店铺名或者京东下单链接

    def __init__(self, tid, uname):
        self.tid = tid
        self.uname = uname
        self.yaml = YAML(os.path.join(base_Dir, 'data', 'data.yaml'))
        self.info = self.get_order_info()

    def get_order_info(self):
        """
        查询提交订单所必须的活动参与信息
        :return:
        """
        statement = """SELECT
                        t.source,
                        t.type,
                        t.url_order,
                        ts.taobao_shop,
                        j.jid,
                        j.buyer_uid as uid
                    FROM
                        sk_try t
                    LEFT JOIN sk_try_search ts ON t.tid = ts.tid
                    LEFT JOIN sk_join j ON t.tid = j.tid
                    WHERE
                        t.tid = %s
                    AND j.buyer_uname = %s"""
        params = (self.tid, self.uname,)
        value = get_sql_info(statement, params, meta={
            "info": "查询提交订单所必须的活动参与信息"
        })
        return value[0]

    def generate_random_nums(self, source, suffix):
        """
        根据活动来源生成对应随机数量订单号,淘宝后四位需要校验绑定的
        :param source: 活动来源
        :param suffix: 后四位
        :return:
        """
        if source in ('淘宝', '天猫', '淘宝特价版', '阿里巴巴', '抖音'):  # 商品来源为淘宝天猫
            order_no = ''.join([str(random.randint(0, 9))
                               for i in range(0, 14)])
        elif source in ('京东', '京喜'):  # 商品来源为京东
            order_no = ''.join([str(random.randint(0, 9))
                               for i in range(0, 7)])
        elif source == '拼多多':  # 商品来源为拼多多
            order_no = ''.join([str(random.randint(0, 9)) for i in range(
                0, 6)]) + '-' + ''.join([str(random.randint(0, 9)) for i in range(0, 11)])
        elif source in ('食遍天', '试用联盟'):  # 商品来源为试用联盟、食遍天
            order_no = ''.join([str(random.randint(0, 9))
                               for i in range(0, 7)])
        else:  # 商品来源其它包括：微店、划算自营、其它
            order_no = ''.join([str(random.randint(0, 9))
                               for i in range(0, 2)])
        return order_no + str(suffix)


class AppSubmitOrder(Submit):
    # app提交订单号
    def __init__(self, tid, uname):
        super().__init__(tid, uname)
        self.sign = self.get_sign()

    def get_sign(self):
        """
        app登录凭证
        :return:
        """
        app = AppLogin(self.uname)
        sign = app.appget_sign()
        return sign

    def get_multimode_type(self):
        """
        获取多模式类型
        :return:
        """
        yaml_data = self.yaml.get_data('multimode_type')
        url = yaml_data.get('url') + "?tid=" + str(self.tid) + "&uid=" + str(self.info.get("uid")) + \
            "&sign=" + self.sign + "&client_type=1&version=" + \
            self.yaml.get_data("app_version")
        res = json.loads(requests.get(url).text)
        return res.get("data").get("type")

    def app_verify_shop(self, shop_name):
        """
        提交订单号前先验证店铺
        :param shop_name:
        :return:
        """
        yaml_data = self.yaml.get_data('app_verify_shop')
        yaml_data.get('data').update({
            'uid': self.info.get("uid"),
            'sign': self.sign,
            'shop_name': shop_name,
            'jid': self.info.get("jid")
        })
        response = requests.post(url=yaml_data.get('url'), data=yaml_data.get('data'),
                                 headers=yaml_data.get('header')).text
        if '"code":"OK"' in response:
            logger.debug("验证店铺成功...")
            return True
        else:
            logger.debug("验证店铺失败...")
            return False

    def app_verify_order_way(self, jd_order_url):
        """
        京东来源提交订单号前先验证京东下单地址
        :param jd_order_url:
        :return:
        """
        yaml_data = self.yaml.get_data('app_verify_jd_order')
        yaml_data.get('data').update({
            'uid': self.info.get("uid"),
            'sign': self.sign,
            'order_url': jd_order_url,
            'jid': self.info.get("jid")
        })
        response = requests.get(
            yaml_data.get('url'),
            params=yaml_data.get('data'),
            headers=yaml_data.get('header')).text
        if '"code":"OK"' in response:
            logger.debug("验证下单链接成功...")
            return True
        else:
            logger.debug("验证下单链接失败...")
            return False

    def app_submit_order_no(self, no):
        """
        app端活动填写订单号
        :param no:
        :return:
        """
        yaml_data = self.yaml.get_data('app_submit_order')
        yaml_data.get('data').update({
            'uid': self.info.get("uid"),
            'sign': self.sign,
            'no': no,
            'jid': self.info.get("jid")
        })
        return requests.post(url=yaml_data.get('url'), data=yaml_data.get(
            'data'), headers=yaml_data.get('header')).text

    def app_modify_order_no(self, no):
        """
        app端活动修改订单号
        :param no:订单号
        :return:
        """
        yaml_data = self.yaml.get_data('app_modify_order')
        yaml_data.get('data').update({
            'uid': self.info.get("uid"),
            'sign': self.sign,
            'no': no,
            'jid': self.info.get("jid")
        })
        return requests.post(url=yaml_data.get('url'), data=yaml_data.get('data'),
                             headers=yaml_data.get('header')).text

    def app_submit_no(self, flag=1):
        """
        app端提交订单号，搜索类活动需要验证店铺或者链接
        :param flag:区别修改订单号还是提交订单号
        :return:
        """
        # 如果用户状态不对，改为正常
        account_status = change_user_account_status(self.uname)
        # 没绑淘宝就开始绑订
        tb_status = bind_tb(self.uname)
        if not(account_status and tb_status):
            return False
        if self.info.get("type") == 17:
            multimode_type = self.get_multimode_type()
            # type = Submit.get_dic_value(typev,int(multimode_type))
            type_name = Type(int(multimode_type)).name  # 通过枚举值来取枚举name
        else:
            type_name = Type(self.info.get("type")).name
        # source = Submit.get_dic_value(sourcev,source)
        source = Source(self.info.get("source")).name
        if type_name in Submit.app_type:
            logger.debug("该活动为APP活动...")
            if type_name in Submit.need_verify_order_way:
                if source != '京东':
                    logger.debug("该活动为app搜索类型活动且来源非京东,提交订单号前需验证店铺名称...")
                    logger.debug("开始验证店铺...")
                    shop_name = self.info.get("taobao_shop")
                    status = self.app_verify_shop(shop_name)
                    if status:
                        logger.debug("验证店铺成功...")
                    else:
                        logger.debug("验证店铺失败...")
                else:
                    logger.debug("该活动为app搜索类型活动且来源为京东,提交订单号前需验证京东下单链接...")
                    logger.debug("开始验证京东下单链接...")
                    jd_order_url = self.info.get("url_order")
                    status = self.app_verify_order_way(jd_order_url)
                    if status:
                        logger.debug("验证京东下单链接成功...")
                    else:
                        logger.debug("验证京东下单链接失败...")
            else:
                logger.debug("该活动不是app搜索类型活动")
                # print("该活动不是app搜索类型活动")
            statement = """select valid_trade_suffix from sk_user_bind_taobao where uid = %s"""
            suffix = get_sql_info(statement, (self.info.get("uid"),), meta={
                "info": "查询绑定淘宝号的后四位数字"
            })
            order_no = self.generate_random_nums(
                source, suffix[0].get('valid_trade_suffix'))
            if flag != 1:
                logger.debug("开始修改订单号...")
                response_data = self.app_modify_order_no(order_no)
            else:
                logger.debug("开始提交订单号...")
                response_data = self.app_submit_order_no(order_no)
            logger.debug(response_data)
            assert_result_dict(response_data, self.uname + '提交订单号：' + order_no)
        else:
            logger.info("不是app活动")


class PcSubmitOrder(Submit):
    # PC端活动提交订单号
    def __init__(self, tid, uname):
        super().__init__(tid, uname)
        self.session = self.get_session()

    def get_session(self):
        """
        :return:返回登录用户session
        """
        login = PcLogin(self.uname)
        login.pc_login()
        return login.get_session()

    def pc_submit_no(self):
        """
        PC端活动填写订单号
        :param tid:
        :return:
        """
        status = change_user_account_status(self.uname)
        if not status:
            return False
        logger.debug("开始执行PC端用户提交订单号操作...")
        type_name = Type(self.info.get("type")).name
        source = Source(self.info.get("source")).name
        statement = """select valid_trade_suffix from sk_user_bind_taobao where uid = %s"""
        suffix = get_sql_info(statement, (self.info.get("uid"),), meta={
            "info": "查询绑定淘宝号的后四位数字"
        })
        order_no = self.generate_random_nums(
            source, suffix[0].get('valid_trade_suffix'))
        yaml_data = self.yaml.get_data('pc_submit_order')
        if type_name == "TYPE_SEARCH":
            verify_value = ''
            if source in ('淘宝', '天猫', '阿里巴巴', '划算自营'):
                logger.debug("该活动为PC端搜索下单活动，提交订单号需校验店铺名称...")
                verify_value = self.info.get("taobao_shop")
            elif source == '京东':
                logger.debug("该活动为PC端搜索下单活动，提交订单号需校验下单链接...")
                verify_value = self.info.get("url_order")
            yaml_data.get('data').update({
                'tid': self.tid,
                'jid': self.info.get("jid"),
                'tradeorderno': order_no,
                'url_order': verify_value
            })
        else:
            yaml_data.get('data').update({
                'tid': self.tid,
                'jid': self.info.get("jid"),
                'tradeorderno': order_no
            })
            yaml_data.get('data').pop('url_order')
        response = self.session.post(url=yaml_data.get('url'), data=yaml_data.get('data'),
                                     headers=yaml_data.get('header')).text
        assert_result_dict(response, self.uname + '提交订单号：' + order_no)


def main():
    while True:
        # 显示功能菜单
        menu_list.submit_order_menu()
        # 选择
        choise = input("请输入您的选择: ")
        if choise in ('q', 'Q'):
            break
        try:
            tid = int(input(u'请输入活动tid: '))
            status = check_tid(tid)
            if not status:
                raise Exception("活动tid不存在try表，请核实后在重新输入")
        except Exception as e:
            logger.error("reszon => %s" % e)
        else:
            buyer_name = input(u'请输入要提交单号的试客名称: ')
            if choise == '1':
                pc_submit = PcSubmitOrder(tid, buyer_name)
                pc_submit.pc_submit_no()
            elif choise == '2':
                app_submit = AppSubmitOrder(tid, buyer_name)
                app_submit.app_submit_no(flag=1)
            elif choise == '3':
                app_submit = AppSubmitOrder(tid, buyer_name)
                app_submit.app_submit_no(flag=2)
            else:
                logger.info("没有对应的选项,请按选项输入...")
                break


if __name__ == "__main__":
    main()
    # get_dic_value(typev,8)
